package xyz.fefine;

import java.util.List;

/**
 * Created by feng_ on 2016/9/8.
 */
public class IfStmnt extends ASTList {
    public IfStmnt(List<ASTree> list) {
        super(list);
    }
    public ASTree condition(){
        return child(0);
    }
    public BlockStmnt thenBlock(){
        return (BlockStmnt) child(1);
    }
    public BlockStmnt elseBlock(){
        return numChildren() > 2 ? (BlockStmnt)child(2) : null;
    }

    @Override
    public String toString() {
        return "( if " + condition() +" "+ thenBlock() + " else " + elseBlock() + ")";
    }

    @Override
    public Object eval(Enviorment enviorment) {
        int res = (int)condition().eval(enviorment);
        if (res == TRUE) {
            return thenBlock().eval(enviorment);
        }
        if (elseBlock() != null) {
            return elseBlock().eval(enviorment);
        }
        return res;
    }
}
